<template>
  <el-container>
    <el-dialog
      v-model="dialogVisible"
      title="新增操作"
      width="30%"
      center
      
      draggable
    >
      <el-form
        :model="form"
        class="addform"
        label-width="auto"
        :rules="addrules"
        ref="ruleFormRef"
        status-icon
      >
        <el-form-item label="用户名:" prop="uname">
          <el-input v-model="form.uname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model.number="form.phone" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="来源地:" prop="address">
          <el-cascader
            size="large"
            style="width: 100%"
            :options="options"
            v-model="form.address"
            autocomplete="off"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="备注:" prop="remark">
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmadd(form, selectedOptions)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editVisible"
      title="编辑操作"
      width="30%"
      center
      draggable
    >
      <el-form
        :model="editform"
        class="addform"
        status-icon
        label-width="auto"
        :rules="addrules"
        ref="editFormRef"
      >
        <el-form-item label="用户名:" prop="uname">
          <el-input v-model="editform.uname" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="电话:" prop="phone">
          <el-input v-model.number="editform.phone"></el-input>
        </el-form-item>

        <el-form-item label="来源地:" prop="address">
          <el-cascader
            size="large"
            style="width: 100%"
            :options="options"
            v-model="editform.address"
            autocomplete="off"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="备注:" prop="remark">
          <el-input v-model="editform.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmedit(editform)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-header class="head">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="input1" placeholder="请输入矿泉水名字">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="2">
          <el-button type="primary" @click="select(input1)">查询</el-button>
        </el-col>

        <el-col :span="8"></el-col>
        <el-col :span="3"><span>用户表</span></el-col>
      </el-row>
    </el-header>

    <el-main class="table-box">
      <el-table
        :data="tableData"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="changemult"
      >
        <el-table-column type="selection" width="100" />
        <el-table-column
          type="index"
          width="50"
          :index="indexMethod"
          label="编号"
        />
        <el-table-column prop="uname" label="用户名" width="300">
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="200">
        </el-table-column>
        <el-table-column prop="address" label="地址" width="200">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="200">
        </el-table-column>

        <el-table-column label="单项操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <div class="pagin">
      <el-pagination
        layout="prev, pager, next"
        :total="totalNumber"
        :page-size="Pagesize"
        :pager-count="10"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </el-container>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import {
  getuser,
  getuserdata,
  updateuserbyid,
  saveuser,
  deleteuserbyid,
} from "@/apis/userData.js";
import { Search } from "@element-plus/icons-vue";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {
    Search,
  },
  name: "Region",
  data() {
    return {
      options: regionData,
      selectedOptions: ["440000", "440100", "440101"],
    };
  },

  setup() {
    let multipleSelection = ref([]);
    const input1 = ref("");
    const dialogVisible = ref(false);
    let totalNumber = ref(0);
    let currentPage = ref(1);
    let Pagesize = ref(5);
    let editVisible = ref(false);

    let listdata = ref("");
    let tableData = ref("");

    const form = reactive({
      uid: "",
      uname: "",
      phone: "",
      address: ["440000", "440100", "440101"],
      remark: "",
    });

    const editform = reactive({
      uid: "",
      uname: "",
      phone: "",
      address: "",
      remark: "",
    });

     const checkphone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入电话"));
      }
      setTimeout(() => {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        const isPhone = reg.test(value);
        value = Number(value); //转换为数字
        if (typeof value === "number" && !isNaN(value)) {
          //判断是否为数字
          value = value.toString(); //转换成字符串
          if (value.length < 0 || value.length > 12 || !isPhone) {
            //判断是否为11位手机号
            callback(new Error("手机号码格式是11位"));
          } else {
            callback();
          }
        }
      }, 100);
    };

    const addrules = reactive({
      uname: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      phone: [
        { validator: checkphone, trigger: "blur" }
        ],
      address: [
        {
          required: true,
          message: "请选择地址",
          trigger: "blur",
        },
      ],
      remark: [
        {
          required: true,
          message: "请输入备注",
          trigger: "blur",
        },
      ],
    });




    onMounted(() => {
      getdata();
    });


    function getdata() {
      let page = currentPage.value;
      let size = Pagesize.value;
      getuser().then((res) => {
        listdata.value = res.data.page.list;
        totalNumber.value = res.data.page.list.length;
        tableData.value = res.data.page.list.slice(
          page * size - size,
          page * size
        );
      });
    }

    function select(prop) {
      let name = { key: prop };
      getuserdata(name).then((res) => {
        window.console.log(res.data.page.list);
        listdata.value = res.data.page.list;
        totalNumber.value = res.data.page.list.length;
        currentPage.value = 1;
        tableData.value = res.data.page.list.slice(0, Pagesize.value);
      });
    }

    function handleEdit(index, row) {
      editVisible.value = true;
      let place = row.address.split("-");
      let first = TextToCode[place[0]].code;
      let second = TextToCode[place[0]][place[1]].code;
      let third = TextToCode[place[0]][place[1]][place[2]].code;

      editform.address = [first, second, third];
      editform.uid = row.uid;
      editform.uname = row.uname;
      editform.phone = parseInt(row.phone);
      editform.remark = row.remark;
    }

    function confirmadd(form, selectedOptions) {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          form.place =
            CodeToText[selectedOptions[0]] +
            "-" +
            CodeToText[selectedOptions[1]] +
            "-" +
            CodeToText[selectedOptions[2]];

          saveuser(form)
            .then((res) => {
              window.console.log(res.data);
              if (res.data.code == 0) {
                ElMessage({
                  message: "新增成功",
                  type: "success",
                });
                getdata();
              }
            })
            .catch(function (err) {
              ElMessage({
                message: "表单已存在,错误原因:" + err,
                type: "error",
              });
            });
          dialogVisible.value = false;
        } else {
          ElMessage({
            message: "输入表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function confirmedit(form) {

      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          form.address =
            CodeToText[form.address[0]] +
            "-" +
            CodeToText[form.address[1]] +
            "-" +
            CodeToText[form.address[2]];

          updateuserbyid(form).then((res) => {
            if (res.data.code == 0) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              getdata();
            } else {
              ElMessage({
                message: "编辑失败",
                type: "error",
              });
            }
          });
          editVisible.value = false;
        } else {
          ElMessage({
            message: "编辑表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function handleCurrentChange(page) {
      currentPage.value = page;
      let size = Pagesize.value;
      tableData.value = listdata.value.slice(page * size - size, page * size);
    }

    function indexMethod(index) {
      return index + 1 + (currentPage.value - 1) * Pagesize.value;
    }

    function changemult(val) {
      let ids = [];
      for (let i in val) {
        ids.push(val[i].uid);
      }
      multipleSelection.value = ids;
    }

    function alldelete(data) {
      if (data.length == 0) {
        ElMessage({
          message: "你好像没有选中删除的数据项",
          type: "warning",
        });
      } else {
        deleteuserbyid(data).then((res) => {
          if (res.data.code == 0) {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            getdata();
          } else {
            ElMessage({
              message: "删除失败",
              type: "error",
            });
          }
        });
      }
    }

    function handleDelete(index, row) {
      //删除操作
      let shid = [row.uid];

      deleteuserbyid(shid).then((res) => {
        if (res.data.code == 0) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getdata();
        } else {
          ElMessage({
            message: "删除失败",
            type: "error",
          });
        }
      });
    }

    return {
      input1,
      tableData,
      multipleSelection,
      dialogVisible,
      editVisible,
      select,
      addrules,
      confirmadd,
      indexMethod,
      editform,
      totalNumber,
      currentPage,
      Pagesize,
      handleEdit,
      confirmedit,
      alldelete,
      handleDelete,
      form,
      changemult,
      handleCurrentChange,
    };
  },
});
</script>
<style scoped>
.head {
  font-size: 18px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.addform >>> .el-form-item {
  padding-left: 8%;
}
.addform >>> .el-input {
  width: 80%;
}
.pagin {
  text-align: center;
  margin-left: -10%;
}
</style>